import {
	getNeedLoginPages,
	needLoginPages
} from '@/utils/router/pages'
import { log } from '@/utils/log'
import { useAppStore } from "@/store/app";
import { useUserStore } from "@/store/user";

// 登录页面路径
const loginRoute = '/pages/login/index'

const isDev = import.meta.env.DEV

// 黑名单登录拦截器 - （适用于大部分页面不需要登录，少部分页面需要登录）
const navigateToInterceptor = {
	// 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同
	invoke({
		url
	}) {
		const appStore = useAppStore()
		const userStore = useUserStore()
		const path = url.split('?')[0]
		
		
		//判断是否需要登录
		const isNeedLogin = needLoginPages.includes(path)
		if (!isNeedLogin || userStore.isLogin) {
			
			if(!path.includes('/pages/login')){
				appStore.lastPage = url
			}
			
			return true
		}else{
			appStore.redirect = url
			const redirectRoute = `${loginRoute}?redirect=${url}`
			uni.navigateTo({
				url: redirectRoute
			})
			log.success(`路由拦截器`,`由${url}重定向至${redirectRoute}`)
			
			return false
		}
		
		
	},
	success(args) {
		
		log.success(`路由拦截器成功回调`,JSON.stringify(args))
	},
	fail(err) {
		log.success(`路由拦截器失败回调`,JSON.stringify(err))
		//预防页面栈溢出
		if(err.errMsg.includes('limit exceed')){
			const appStore = useAppStore()
			uni.redirectTo({
				url:appStore.lastPage
			})
		}
	},
	complete(res) {
	}
}

export const routeInterceptor = {
	install(app, options) {
		uni.addInterceptor('navigateTo', navigateToInterceptor)
		uni.addInterceptor('reLaunch', navigateToInterceptor)
		uni.addInterceptor('redirectTo', navigateToInterceptor)
		uni.addInterceptor('switchTab', navigateToInterceptor)
	}
}